<template>
  <div id="Check-in">
      <div class="address">
        <h3>入住管理</h3>
      </div>
      <div class="add">
        <el-button @click="addOneCheckOrder">新增订单</el-button>
      </div>
      <div class="show-sales"> 
        <el-scrollbar style="height: 100%;"> <!-- 滚动条 -->
          <el-table
            class="room-type-table TABLEMINWIDH"
            ref="multipleTable"
            :data="checkInOrder"
            :key="updateTableKey"
            tooltip-effect="dark"
            style="width: 100%;font-size: 1.5rem;">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <div class="detail">
                  <div class="left">
                    <img src="@/assets/images/单人大床房.webp" >
                    <div class="info">
                      <div class="oneRow">
                        <span class="label">订单号</span><span class="value">{{scope.row.ocin}}</span>
                      </div>
                      <div class="oneRow">
                        <span class="label">门牌</span><span class="value">{{scope.row.roomPlate}}</span>
                      </div>
                      <div class="oneRow">
                        <span class="label">入住时间</span><span class="value">{{timeFormatter(scope.row.checkInTime)}}</span>
                      </div>
                      <div class="oneRow">
                        <span class="label">离开时间</span><span class="value">{{timeFormatter(scope.row.checkOutTime)}}</span>
                      </div>
                      <div class="oneRow">
                        <span class="label">总价</span><span class="value" style="color:red"><i class="hotel-management-icon icon-renminbi1688"></i>{{scope.row.finalPrice}}</span>
                      </div>
                      <div class="oneRow">
                        <span class="label">入住状态</span><span class="value">{{checkInStatus[scope.row.csin]}}</span>
                      </div>
                    </div>
                  </div>
                  <div class="right">
                    <el-scrollbar style="height: 100%;">
                      <div class="oneMan" v-for="cust in customer[scope.$index][0]" :key="cust.ocin">
                        <div class="image" :style="{borderColor:memberColor[scope.row.vipLevel]}">
                         <i class="hotel-management-icon icon-zuozhe"></i>
                        </div>
                        <div class="info">
                          <div class="oneRow">
                            <span class="label">姓名</span><span class="value">{{cust.roomerName}}</span>
                          </div>
                          <div class="oneRow">
                            <span class="label">身份证</span><span class="value">{{cust.roomerID}}</span>
                          </div>
                          <div class="oneRow">
                            <span class="label">手机号码</span><span class="value">{{checkInOrder[scope.$index].vip}}</span>
                          </div>
                          <div class="oneRow">
                            <span class="label">等级</span><span class="value" :style="{color:memberColor[scope.row.vipLevel]}">
                              <i class="hotel-management-icon icon-huangguanguanjundiyihuiyuan"></i>{{memberPreName[scope.row.vipLevel] + '会员'}}
                              </span>
                          </div>
                        </div>
                      </div>
                    </el-scrollbar>
                  </div>
                </div>
              </template>
            </el-table-column>
            <!-- 订单号 -->
            <el-table-column
              label="订单号"
              prop="ocin"
              header-align="center"
              align="center"
              min-width="10%">
            </el-table-column>
            <!-- 门牌 -->
            <el-table-column
              label="门牌"
              header-align="center"
              align="center"
              min-width="15%">
              <template slot-scope="scope">
                <span v-if="scope.$index !== isEditNew">{{scope.row.roomPlate}}</span>
                <div v-else>
                  <div class="block">
                    <el-cascader
                      v-model="newPlateValue"
                      :options="options">
                    </el-cascader>
                  </div>
                </div>
              </template>
            </el-table-column>
            <!-- 入住时间-->
            <el-table-column
              label="入住时间"
              header-align="center"
              align="center"
              min-width="25%">
              <template slot-scope="scope">
                <p><span>from : {{timeFormatter(scope.row.checkInTime)}}</span></p>
                <span>to : {{timeFormatter(scope.row.checkOutTime)}}</span>
              </template>
            </el-table-column>
            <!-- 总价 -->
            <el-table-column
              label="总价"
              header-align="center"
              align="center"
              min-width="10%"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span style="color:red"><i class="hotel-management-icon icon-renminbi1688"></i>{{scope.row.finalPrice}}</span>
              </template>
            </el-table-column>
            <!-- 入住状态 -->
            <el-table-column
              label="入住状态"
              header-align="center"
              align="center"
              min-width="10%">
              <template slot-scope="scope">
                <span>{{checkInStatus[scope.row.csin]}}</span>
              </template>
            </el-table-column>
            <!-- 操作 -->
            <el-table-column
              prop="description"
              header-align="center"
              align="center"
              min-width="20%">
              <template slot-scope="scope">
                <div class="editCheckIn" v-if="scope.row.csin === 1">
                  <div v-if="scope.$index === isEditNew">
                    <el-button size="small" type="primary" @click="cancelOrder(scope.row)">取消</el-button>
                    <el-button size="small" type="primary" @click="saveOrder(scope.row)">保存</el-button>
                  </div>
                  <div v-else>
                    <el-button size="small" type="primary" @click="changeRoom(scope.row)">更换房间</el-button>
                    <el-button size="small" type="primary" @click="leaveRoome(scope.row)">离店</el-button>
                    <el-button size="small" type="danger" @click="returnRoom(scope.row)">退房</el-button>
                  </div>
                </div>
                <div v-else>
                  <span style="color:red">done!</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar><!-- /滚动条 -->
      </div>
      <el-dialog title='入住订单' :visible.sync="dialogTableVisible" :close-on-click-modal="false">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="订单号">
            {{form.ocin}}
          </el-form-item>
          <el-form-item label="入住时间" class="checkInTime">
            <span v-if="isShowSummitButton">{{form.checkInTime}}</span>
            <div v-else>
              <el-date-picker class="item" style="width: 30%;" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期"  v-model="form.checkInTime"></el-date-picker>
              <span class="line">-</span>
              <el-time-picker style="width: 30%;" placeholder="选择时间"  type="date" value-format="yyyy-MM-dd HH:mm:ss"  v-model="form.checkInTime" ></el-time-picker>
            </div>
          </el-form-item>
          <el-form-item label="离开时间" class="checkInTime">
            <span v-if="isShowSummitButton">{{form.checkOutTime}}</span>
            <div v-else>
              <el-date-picker style="width: 30%;" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期" v-model="form.checkOutTime"></el-date-picker>
              <span class="line">-</span>
              <el-time-picker style="width: 30%;" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择时间" v-model="form.checkOutTime"></el-time-picker>
            </div>
          </el-form-item>
          <el-form-item label="房间">
            <div>
              <span v-if="isShowSummitButton">{{form.roomTypeTitle}} / {{form.roomPlate}}</span>
              <div v-else>
                <div class="block">
                  <el-cascader
                    v-model="newPlateValue"
                    :options="options">
                  </el-cascader>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="预订单">
            <span v-if="!form.obin">无</span>
            {{form.obin}}
          </el-form-item>
          <el-form-item label="入住状态">
            <span>{{checkInStatus[form.csin]}}</span>
          </el-form-item>
          <el-form-item label="vip卡号">
            <!-- {{form.vip}} {{form.vipLevel}} {{form.discount}} -->
            <span v-if="isShowSummitButton">{{form.vip}}</span>
            <div v-else>
              <el-input v-model="form.vip" style="width:300px" placeholder="请输入"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="顾客" v-for="cust in customers" :key="cust.id">
            <div v-if="isShowSummitButton">
              <span class="customer-text">名字 : {{cust.roomerName}}</span>
              <span class="customer-text">身份证 :  {{cust.roomerID}}</span> 
            </div>
            <div v-else> 
              <span class="customer-text1">名字 :</span> <el-input class="customer" v-model="cust.roomerName"></el-input><br>
              <span class="customer-text1">身份证 :</span> <el-input class="customer" v-model="cust.roomerID" style="margin-top: 20px;"></el-input>
            </div>
          </el-form-item>
          <el-form-item class="btMeter" v-if="!isShowSummitButton">
            <div >
              <el-button @click="addCustomer"><i class="el-icon-plus"></i></el-button>
              <span class="block"></span>
            </div>
          </el-form-item>
          <el-form-item label="价格" v-if="form.roomPrice">
            {{form.roomPrice}}
            <span style="color:red">* {{discount[form.vipLevel]}}</span> 
          </el-form-item>
          <el-form-item label="总价" v-if="form.roomPrice" style="color:red">
            {{form.finalPrice}}
          </el-form-item>
          <el-form-item label="订单时间" v-if="form.orderTime">
            {{form.orderTime}}
          </el-form-item>
          <el-form-item class="btMeter">
            <div v-if="isShowSummitButton">
              <el-button @click="summitOrder">提交订单</el-button>
              <span class="block"></span>
            </div>
            <div v-else>
               <el-button @click="createOrder">生成订单</el-button>
               <span class="block"></span>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
  </div>
</template>

<script>
import { timeFormatter, timeFormatter2 } from '@/utils/utils'
import { showMessage } from '@/utils/utils'
import { roomTypeMixin } from '@/utils/mixins/roomType'
import { loadingMixin } from '@/utils/mixins/loading'
import { getAllBookOrder, getAllCustomersInCheckIiOrder, getAllCheckInOrder, modifyOneCheckInOrder, addOneCustomerInCheckInOrder, getOneVip, addOneCheckInOrder, modifyOneBookOrder, getAllUnuseRoom } from '@/api/api'
export default {
  mixins: [ loadingMixin, roomTypeMixin ],
  name: 'Check-in-management',
  data() {
    return {
      memberPreName:['普通', '青铜', '白银', '黄金', '铂金', '钻石', '至尊', '全部', '排序'],
      memberColor:['gray', 'green', 'lightgray', 'gold', 'darkslateblue', 'deepskyblue', 'purple'],
      customers : [
        { roomerName: '', roomerID: '', ocin: -1},
      ],
      dialogTableVisible: false,
      checkInOrder: [],
      checkInStatus: ['已离店', '已入住', '已更换', '已退款'],
      discount: [1, 0.98, 0.95, 0.9, 0.88, 0.8, 0.75],

      updateTableKey: Math.random(),

      customer:[
        // {'roomerName':'李华', 'roomerID':'4441821...','ocin':'152'},
        // {'roomerName':'李华', 'roomerID':'4441821...','ocin':'152'},
      ],

      isEditNewRow: -1,
      // 更换的编辑
      isEditNew: -1,
      options: [
        // { 
        //   value:'单人大床房', label: '单人大床房', 
        //   children: [
        //     {value:'plate', label: '1201'},
        //     {value:'plate', label: '1202'},
        //     {value:'1203', label: '1203'},
        //   ]
        // }
      ],
      newPlateValue: [],

      form: {
        "orderTime": null,
        "checkInTime":"",
        "checkOutTime":"",
        "roomTypeTitle":"",
        "roomPlate":"",
        "roomPrice":0,
        "vipLevel":0,
        "discount":1,
        "finalPrice": 0,
        "obin":null,
        "ocin":40,
        "csin":1,
        "vip":''
      },
      isShowSummitButton: false
    }
  },
  methods: {
    timeFormatter,
    // 增加顾客
    addCustomer() {
      this.customers.push({ roomerName: '', roomerID: '', ocin: -1})
    },
    // 提交订单 2020-02-04T18:00:00.000+0000
    async summitOrder() {
      let obj = { ...this.form }
      obj.checkInTime = this.form.checkInTime.slice(0, 10) + "T" + this.form.checkInTime.slice(11) + '.000+0000'
      obj.checkOutTime = this.form.checkOutTime.slice(0, 10) + "T" + this.form.checkOutTime.slice(11) + '.000+0000'
      obj.orderTime = this.form.orderTime.slice(0, 10) + "T" + this.form.orderTime.slice(11) + '.000+0000'
      obj.vip *= 1
      obj.roomPlate = obj.roomPlate.toString()
      obj.discount = parseFloat(obj.discount) 

      //增加orderCheckx信息
      await Promise.resolve(addOneCheckInOrder(obj).then(response => {
          if(response.data === '添加成功!') {
            showMessage(this, '保存成功', 'success')
            if(this.isEditNew !== -1) this.isEditNew = -1
            if(this.dialogTableVisible) this.dialogTableVisible = false
          }
        }).catch(error => showMessage(this, '新增入住订单失败！', 'error'))
      )

      // 增加顾客信息
      for(let obj of this.customers) {
        obj.ocin = this.form.ocin
        await Promise.resolve(addOneCustomerInCheckInOrder(obj).then(response => {})
          .catch(error => showMessage(this, '添加访客记录失败！', 'error'))
        ) 
      }
    },
    // 生成订单
    createOrder() {
      for(let o of this.roomTypes) {
        if(o.tin === this.newPlateValue[0]) this.form.roomTypeTitle = this.roomTypes[this.newPlateValue[0]].title
      }

      getOneVip(this.form.vip).then(response => {
        if(response.data) {
          this.form.vipLevel = response.data.lv
          this.form.discount = this.discount[this.form.vipLevel]
        } else {
          this.form.vipLevel = 0
          this.form.discount = 1
        }
        this.form.roomPrice = this.roomTypes[this.newPlateValue[0]].price
        this.form.finalPrice = this.form.roomPrice * this.form.discount
        this.form.roomPlate = this.newPlateValue[1]
        this.form.orderTime = timeFormatter2(new Date(),"yyyy-MM-dd hh:mm:ss")
        this.isShowSummitButton = true
      }).catch(error => showMessage(this, '获取所有一个vip信息失败', 'error'))
    },
    // 现场开订单
    addOneCheckOrder() {
      let maxOcin = 0
      for(let o of this.checkInOrder) {
        if(o.ocin > maxOcin) maxOcin = o.ocin
      }
      this.form.ocin = maxOcin + 1
      this.customers = [
        { roomerName: '', roomerID: '', ocin: -1},
      ]
      this.dialogTableVisible = true
    },
    // 保存更新后的新增
    saveOrder(row) {
      for(let o of this.roomTypes) {
        if(o.tin === this.newPlateValue[0]) row['roomTypeTitle'] = o.title
      }
      row['roomPlate'] = this.newPlateValue[1]

      addOneCheckInOrder(row).then(response => {
        if(response.data === '添加成功!') {
          showMessage(this, '保存成功', 'success')
          if(this.isEditNew !== -1) this.isEditNew = -1
          if(this.dialogTableVisible) this.dialogTableVisible = false
        }
      }).catch(error => showMessage(this, '新增入住订单失败！', 'error'))
    },
    // 取消更换后的新增
    cancelOrder(row) {
      this.checkInOrder.splice(0, 1)
      this.isEditNew = -1
    },
    // 新增一行
    addOneRow(row) {
      let maxOcin = 0
      for(let o of this.checkInOrder) {
        if(o.ocin > maxOcin) maxOcin = o.ocin
      }
      this.isEditNew = 0
      let obj = { ...row }
      obj['csin'] = 1
      obj['ocin'] = maxOcin + 1
      this.checkInOrder.splice(0, 0, obj)
    },
    // 更换房间
    changeRoom(row) {
      this.updateAllUnuseRoom()
      this.modifyOneOrder(row, 2)
    },
    // 离店
    leaveRoome(row) {
      this.modifyOneOrder(row, 0)
    },
    // 退房
    returnRoom(row) {
      this.modifyOneOrder(row, 3)
    },
    // 修改订单
    modifyOneOrder(row, status) {
      let obj = { ...row }
      obj['csin'] = status
      modifyOneCheckInOrder(obj.obin, obj).then(response => {
        if(response.data === '修改成功！') {
          showMessage(this, '保存成功' ,'success')
          row['csin'] = status
          if(status === 2) this.addOneRow(row)
        }
      })
    },
    // 更新所有可使用房间
    updateAllUnuseRoom() {
      return Promise.resolve(getAllUnuseRoom().then(response => {
          // 返回的数组从1开始
          response.data.splice(0, 1)
          if(response.data) {
            for(let id in response.data) {
              let obj = {}
              if(response.data[id]) {
                obj['value'] = this.roomTypes[id].tin
                obj['label'] = this.roomTypes[id].title
                obj['children'] = []
                for(let arr2 of response.data[id]) {
                  obj['children'].push({ value: arr2.rin, label: arr2.rin})
                }
              }
              this.options.push(obj)
            }
          }
        }).catch(error => showMessage(this, '获取所有可使用房间失败', 'error'))
      )
    },
    async load() {
      //获取所有入住订单
      await Promise.resolve(getAllCheckInOrder().then(response => {    
        this.checkInOrder = response.data.reverse()
      }).catch(error => showMessage(this, '获取所有入住订单失败！', 'error')))

      for(let i in this.checkInOrder) {
        this.customer.push([])
        await  Promise.resolve(getAllCustomersInCheckIiOrder(this.checkInOrder[i].ocin).then(response => {
            response.data['vip'] = this.checkInOrder[i].vip
            this.customer[i].push(response.data)
          }).catch(error => showMessage(this, '获取订单的房客失败！', 'error'))
        ) 
      }

      await this.updateRoomType()

      await this.updateAllUnuseRoom()
    }
  },
}
</script>

<style>
#Check-in .el-scrollbar__wrap {
  overflow-x: hidden;
}
#Check-in .el-table__row:hover .editCheckIn{
  display: block;
}
/* #Check-in  */
</style>
<style lang="less" scope>
.address{
  position: relative;
  color: #aa97b0;
  top: -20px;
}
.customer{
  width: 400px;
}
.customer-text{
  display: inline-block;
  width: 230px;
}
.customer-text1{
  display: inline-block;
  width: 50px;
}
.checkInTime{
  .line{
    margin-left: 20px;
    margin-right: 20px;
  }
}
.add{
  width: 100%;
  background-color: #ffffff;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.editCheckIn{
  display: none;
}
.detail{
  display: flex;
  .left{
    // background-color: aqua;
    width: 600px;
    margin-left: 20px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    img{
      width: 300px;
      height: 240px;
      margin-right: 20px;
    }
    .info{
      .oneRow{
        width: 250px;
        height: 40px;
        font-size: 14px;
        .label{
          display: inline-block;
          width: 80px;
          color: #99A9BF;
        }
        .value{
          display: inline-block;
          width: 150px;
        }
      }
    }
  }
  .right{
    float: left;
    // min-width: 400px;
    // background-color: aqua;
    border-left: 1px solid rgb(209, 137, 3);
    box-sizing: border-box;
    padding-left: 40px;
    .oneMan{
      display: flex;
      align-items: center;
      .image{
        box-sizing: border-box;
        width: 100px;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 2px solid gray;
        margin-right: 20px;
        i{
          font-size: 4rem;
          color: gray;
        }
      }
      .info{
        .oneRow{
            width: 250px;
            height: 40px;
            font-size: 14px;
            .label{
              display: inline-block;
              width: 80px;
              color: #99A9BF;
            }
            .value{
              display: inline-block;
              width: 150px;
            }
          }
      }
    }
  }
}
.btMeter{
  display: flex;
  justify-content: center;
  align-items: center;
  .block{
    display: inline-block;
    width: 78px;
  }
}

</style>